<!-- subpkg_consult/payment/index.vue -->
<script lang="ts" setup>
  import { createConsultOrderApi, saveConsultOrderApi } from '@/apis/consult'
  import { getPatientDetailApi } from '@/apis/patient'
  import { useConsultStore } from '@/stores/consult'
  import type { OrderPreData } from '@/types/consult'
  import type { PatientItem } from '@/types/patient'
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'
  import CustomPayment from '@/components/custom-payment/custom-payment.vue'
  import type { CustomPaymentInstance } from '@/types/components'
  import { orderPayApi } from '@/apis/user'

  const consultStore = useConsultStore()
  const preOrderInfo = ref<OrderPreData>({
    actualPayment: 0,
    couponDeduction: 0,
    payment: 0,
    pointDeduction: 0,
  })

  const getData = async () => {
    console.log(consultStore.type, consultStore.illnessType)
    const res = await createConsultOrderApi({
      type: consultStore.type.toString(),
      illnessType: consultStore.illnessType.toString(),
    })

    preOrderInfo.value = res
    // console.log('预支付信息', preOrderInfo.value)
  }

  const patientInfo = ref<PatientItem>()
  // 获取患者详情
  const getPatientInfo = async () => {
    const res = await getPatientDetailApi(consultStore.patientID)
    patientInfo.value = res
    // console.log(patientInfo.value)
  }

  onLoad(() => {
    getData()
    getPatientInfo()
  })

  const orderId = ref('')

  const customPayment = ref<CustomPaymentInstance>()
  // 打开支付弹层
  const openPayPopup = () => {
    customPayment.value?.open()
  }

  // 创建订单
  const createOrder = async () => {
    const res = await saveConsultOrderApi({
      ...consultStore.illnessInfoStore,
      illnessType: consultStore.illnessType,
      patientId: consultStore.patientID,
      type: consultStore.type,
    })
    // console.log('创建订单', res)
    orderId.value = res.id
    uni.showToast({
      title: '订单创建成功',
      icon: 'success',
    })
    openPayPopup()
  }

  // 立即支付
  const handlePay = async (index: number) => {
    if (index === 0) {
      uni.showToast({
        title: `暂不支持微信支付`,
        icon: 'none',
      })
      return
    }
    uni.showLoading({
      title: '支付中...',
    })
    const res = await orderPayApi({
      orderId: orderId.value,
      paymentMethod: index,
      payCallback: 'http://localhost:5173/#/subpkg_consult/room/room',
    })
    console.log(res)
    uni.hideLoading()
    // #ifdef H5
    location.href = res.payUrl // H5 端改变栏地址为支付 URL
    // #endif
  }

  // 关闭支付
  const closePayment = async () => {
    const res = await uni.showModal({
      title: '温馨提示',
      content: '你确定放弃支付吗？',
      cancelText: '仍要关闭',
      cancelColor: '#848484',
      confirmText: '继续支付',
      confirmColor: '#16C2A3',
    })
    if (res.cancel) {
      // 关闭所有页面，去首页
      uni.reLaunch({ url: '/pages/index/index' })
    }
  }
</script>

<template>
  <scroll-page>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${preOrderInfo?.payment}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${preOrderInfo?.couponDeduction}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ preOrderInfo?.pointDeduction }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ preOrderInfo?.actualPayment }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray"
                >{{ patientInfo?.name }} | {{ patientInfo?.gender }} | {{ patientInfo?.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item
            border
            title="病情描述"
            :note="consultStore.illnessInfoStore.illnessDesc"
          />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ preOrderInfo?.actualPayment }}</text>
      </view>
      <button class="uni-button" @click="createOrder">立即支付</button>
    </view>
    <custom-payment
      ref="customPayment"
      :order-id="orderId"
      :amount="preOrderInfo?.actualPayment"
      @confirm="handlePay"
      @close="closePayment"
    />
  </scroll-page>
</template>

<style lang="scss">
  @import './payment.scss';
</style>
